/**
 * @Author: LiMeng
 * @Date: 2017/5/13
 */
var GLOBAL = {
    ID: '',
    ACTION_URL: ROOT_PATH + '/securityCheck/checkInfo/add.shtml',
    UPDATE_CHECK_DATE_URL: ROOT_PATH + '/securityCheck/checkInfo/updateDate.shtml'
};
var ajaxSuccessHandler = function (result) {
    result = $.parseJSON(result);
    if (result.success) {
        layer.msg(result.message, {time: 1000, icon: 1}, function () {
            WindowManager.closeLayer({returnValue: true});
        });
    } else {
        layer.msg(result.message, {icon: 2});
    }
};
var addCommonFormParams = function (param) {
    param.checkTypeName = $('#checkTypeId').combo('getText');
    param.checkLevelName = $('#checkLevelId').combo('getText');
    param.checkPlanName = $('#checkPlanId').combo('getText');
};
var formSubmitAction = function (url, callback, params) {
    $.messager.progress();	// 显示进度条

    $('#form1').form('submit', {
        url: url,
        onSubmit: function (param) {
            addCommonFormParams(param);
            if ($.isNotEmpty(params)) {
                $.extend(param, params);
            }
            var isValid = $(this).form('validate');
            if (!isValid) {
                $.messager.progress('close');	// 如果表单是无效的则隐藏进度条
            }
            return isValid;	// 返回false终止表单提交
        },
        success: function (result) {
            $.messager.progress('close');	// 如果提交成功则隐藏进度条
            callback(result);
        }
    });
};
var getSelectedCheckUser = function (data) {
    var names = '';
    var ids = '';
    for (var index in data) {
        names += ',' + data[index].realName;
        ids += ',' + data[index].id;
    }

    $('#checkUserNames').textbox('setValue', names.substring(1));
    $('#checkUserIds').val(ids.substring(1));
};
var openSelectUser = function (title, callback) {
    WindowManager.openLayer({
        type: 2,
        title: title,
        area: ['900px', '500px'],
        content: ROOT_PATH + '/permission/user/simpleList.shtml?isMulti=1',
        callBack: callback
    });
};
var addCheckProblem = function () {
    var openAddCheckProblemLayer = function () {
        WindowManager.openLayer({
            type: 2,
            title: '问题登记',
            area: ['1150px', '70%'],
            content: ROOT_PATH + '/securityCheck/checkProblem/add.shtml?checkInfoId=' + GLOBAL.ID,
            callBack: function (data) {
                if (data) {
                    $('#dg1').datagrid('load', {
                        checkInfoId: GLOBAL.ID,
                        sort: 'addTime',
                        order: 'desc'
                    });
                }
            }
        });
    };
    if (GLOBAL.ID !== '') {
        openAddCheckProblemLayer();
    } else {
        formSubmitAction(GLOBAL.ACTION_URL, function (result) {
            result = $.parseJSON(result);
            if (result.success) {
                GLOBAL.ID = result.data.id;
                openAddCheckProblemLayer();
            } else {
                layer.msg(result.message, {icon: 2});
            }
        });
    }
};
var editCheckProblem = function () {
    var $selected = $('#dg1').datagrid('getSelections');
    if ($selected.length !== 1) {
        layer.alert('请选择一个问题！');
        return false;
    }
    WindowManager.openLayer({
        type: 2,
        title: '编辑问题',
        area: ['1150px', '70%'],
        content: ROOT_PATH + '/securityCheck/checkProblem/edit.shtml?' +
        'id=' + $selected[0].id +
        '&checkInfoId=' + GLOBAL.ID,
        callBack: function (data) {
            if (data) {
                $('#dg1').datagrid('load');
            }
        }
    });
};
var deleteCheckProblem = function () {
    var $selected = $('#dg1').datagrid('getSelections');
    if ($selected.length !== 1) {
        layer.alert('请选择一个问题！');
        return false;
    }
    var index = parent.layer.confirm('是否确定删除？', function () {
        $.ajax({
            type: "POST",
            url: ROOT_PATH + '/securityCheck/checkProblem/delete.shtml',
            data: {id: $selected[0].id},
            success: function (result) {
                result = $.parseJSON(result);
                if (result.success) {
                    parent.layer.msg(result.message, {time: 1000, icon: 1}, function () {
                        $('#dg1').datagrid('load');
                        parent.layer.close(index); //先得到当前iframe层的索引
                    });
                } else {
                    parent.layer.msg(result.message);
                }
            }
        });
    });
};
var viewCheckProblem = function (id) {
    WindowManager.openLayer({
        type: 2,
        title: '查看问题',
        area: ['1150px', '70%'],
        content: ROOT_PATH + '/securityCheck/checkProblem/view.shtml?' +
        'id=' + id +
        '&checkInfoId=' + GLOBAL.ID
    });
};
$(function () {

    $('#isFromPlan').combobox({
        onChange: function (newVal) {
            var $checkPlanId = $('#checkPlanId');
            if (newVal === '0') {
                $checkPlanId.combo('disable', true);
            } else {
                $checkPlanId.combo('enable', true);
            }
        }
    });

    $('#checkPlanId').combogrid({
        panelWidth: 600,
        columns: [[
            {field: 'id', title: 'ID', hidden: true},
            {field: 'name', title: '检查计划名称', width: 250},
            {field: 'checkLevelName', title: '检查级别', width: 100},
            {field: 'checkTypeName', title: '检查类型', width: 100}
        ]],
        fitColumns: true,
        pagination: true,
        rownumbers: true,
        sortOrder: true,
        striped: true,
        url: ROOT_PATH + '/securityCheck/checkPlan/validList.shtml',
        idField: 'id',
        textField: 'name',
        queryParams: {
            id: GLOBAL.ID
        },
        required: true,
        editable: false,
        onChange: function () {
            $('#name').textbox('setValue', $(this).combobox('getText'));
        }
    });

    $('#checkTypeId').combobox({
        url: ROOT_PATH + '/permission/dictionary/queryDictionaryByDictionaryTypeCode.shtml?code=' + CONSTANT.DictionaryTypeDefConstants.CHECK_TYPE,
        valueField: 'id',
        required: true,
        editable: false
    });

    $('#checkLevelId').combobox({
        url: ROOT_PATH + '/permission/dictionary/queryDictionaryByDictionaryTypeCode.shtml?code=' + CONSTANT.DictionaryTypeDefConstants.CHECK_LEVEL,
        valueField: 'id',
        required: true,
        editable: false
    });

    $('#checkDeptIds').combotree({
        url: ROOT_PATH + '/permission/department/getDepartmentTree.shtml?parentId=0',
        required: true,
        multiple: true,
        cascadeCheck: false,
        editable: false
    });

    $('#checkUserNames').textbox({
        icons: [{
            iconCls: 'icon-search',
            handler: function () {
                openSelectUser('选择检查人', getSelectedCheckUser);
            }
        }],
        required: true,
        editable: false
    });

    //初始化加载datagrid
    $('#dg1').datagrid({
        method: 'post',
        url: ROOT_PATH + '/securityCheck/checkProblem/list.shtml',
        queryParams: {
            checkInfoId: GLOBAL.ID,
            sort: 'addTime',
            order: 'desc'
        },
        idField: 'id',
        fitColumns: true,
        pagination: true,
        rownumbers: true,
        sortOrder: true,
        striped: true,
        fit: false,
        height: 300,
        singleSelect: true,
        columns: [[
            {field: 'ckid', checkbox: true},
            {
                field: 'remarks', title: '问题描述', width: 200, formatter: function (value, row) {
                return '<a href="javascript:void(0)" onclick="viewCheckProblem(\'' + row.id + '\')" class="easyui-linkbutton text-primary" data-options="plain:true">' + value + '</a>';
            }
            },
            {field: 'receiveDeptNames', title: '被检查单位', width: 120},
            {field: 'contractorAuditName', title: '被检查承包商', width: 120},
            {field: 'checkDate', title: '检查日期', width: 100},
            {field: 'specialtyTypeName', title: '专业分类', width: 80},
            {
                field: 'auditState', title: '状态', width: 80, formatter: function (value) {
                if (value === 0) {
                    return '未下发';
                } else if (value === 1) {
                    return '整改中';
                } else if (value === 2) {
                    return '已验收';
                }
            }
            },
            {
                field: 'rectifyType', title: '整改形式', width: 80, formatter: function (value) {
                if (value === 1) {
                    return '立即整改';
                } else {
                    return '流程整改';
                }
            }
            },
            {field: 'addUserName', title: '登记人', width: 80}
        ]]
    });

    $('#btn_save').on('click', function () {
        if (GLOBAL.ID !== '') {
            $.ajax({
                url: GLOBAL.UPDATE_CHECK_DATE_URL,
                type: 'POST',
                data: {
                    id: GLOBAL.ID
                },
                success: function (result) {
                    ajaxSuccessHandler(result);
                }
            });
        } else {
            formSubmitAction(GLOBAL.ACTION_URL, ajaxSuccessHandler);
        }
    });
    $('#dg1_btn_add').on('click', function () {
        addCheckProblem();
    });
    $('#dg1_btn_edit').on('click', function () {
        editCheckProblem();
    });
    $('#dg1_btn_delete').on('click', function () {
        deleteCheckProblem();
    });
});